﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace delegate_tasks_manager.Delegation_WebPart
{
    class event_Class:SPItemEventReceiver
    {
        public override void ItemAdding(SPItemEventProperties properties)
        {
            SPListItemCollection items = properties.Web.Lists["Delegation_List"].Items;
            try
            {
                foreach (SPListItem item in items)
                {
                    if (item["task_owner"] != null && properties.AfterProperties["AssignedTo"] != null)
                    {
                        SPUser task_owner = properties.Web.EnsureUser(item["task_owner"].ToString());
                        if (properties.AfterProperties["AssignedTo"].ToString() == task_owner.ID.ToString() && Convert.ToDateTime(item["Delegation Start Time"]) < DateTime.Now && Convert.ToDateTime(item["Delegation End Time"]) > DateTime.Now)
                        {
                            SPUser delegate_user = properties.Web.EnsureUser(item["Title"].ToString());
                            properties.AfterProperties["AssignedTo"] = delegate_user.ID;
                            properties.List.Update();
                        }
                    }
                }
            }
            catch (Exception ex)
              { throw ex; }
            
            
        }

        //private string GetClaimBasedUserName(SPUser user)
        //{
        //    string username = string.Empty;
        //    try
        //    {
        //        if (user.IsDomainGroup)
        //        {
        //            if (user.LoginName.StartsWith("c:0+.w|"))
        //            {
        //                username = user.ID.ToString();
        //            }
        //            else
        //                if (user.LoginName.Contains("i:0#.w|"))
        //                {
        //                    username = user.LoginName.Substring(3);
        //                }
        //        }
        //        else
        //        {
        //            if (user.LoginName.StartsWith("i:0#.w|"))
        //            {
        //                username = user.LoginName.Substring(7);
        //            }
        //        }
        //    }
        //    catch{}
        //    return username;
        //} 

    }
}
